package com.traveldesign.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.traveldesign.common.JwtClaimsConstant;
import com.traveldesign.common.QueryPageParam;
import com.traveldesign.common.Result;
import com.traveldesign.entity.Menu;
import com.traveldesign.entity.User;
import com.traveldesign.service.IMenuService;
import com.traveldesign.service.IUserService;
import com.traveldesign.utils.JwtUtil;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wangwang
 * @since 2025-01-20
 */
@RestController
// 允许所有来源的跨域请求（适用于开发环境）
//@CrossOrigin(origins = "*")
@RequestMapping("/admin")
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    //    @GetMapping
//    public  String hello(){
//        return "hello travel";
//    }
    @Resource
    private IUserService userService;
    @Resource
    private IMenuService menuService;
    @GetMapping("/list")
    public List<User> list(){
        return  userService.list();
    }

    @GetMapping("/findByNo")
    public  Result findByNo(@RequestParam String no){
        List list = userService.lambdaQuery().eq(User::getNo,no).list();
        return list.size()>0?Result.suc(list):Result.fail();
    }
    //    新增
    @PostMapping("/save")
    public  Result save(@RequestBody User user){
        return userService.save(user)?Result.suc():Result.fail();
    }
    //     修改
    @PostMapping("/update")
    public   Result update(@RequestBody User user){
        return userService.updateById(user)?Result.suc():Result.fail();
    }
    @GetMapping("/del")
    public   Result del(@RequestParam String id){
        return userService.removeById(id)?Result.suc():Result.fail();
    }
//    登录
    @PostMapping("/login")
    public  Result login(@RequestBody User user){
        List<User> list = userService.lambdaQuery().eq(User::getNo,user.getNo())
                .eq(User::getPassword,user.getPassword()).list();
        // 用户登录后为用户生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, list.get(0).getId());
        String token = JwtUtil.createJWT(claims);
        list.get(0).setToken(token);
        if( list.size() > 0){
            User user1 = (User) list.get(0);
            List menuList  =menuService.lambdaQuery().like(Menu::getMenuRight,user1.getRoleId()).list();
            log.info("{}", menuList);
            HashMap res =new HashMap();
            res.put("user",user1);
            res.put("menu",menuList);
            return   Result.suc(res);
        }
        return  Result.fail();
    }
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        // 检查用户是否已经存在
        List<User> existingUsers = userService.lambdaQuery().eq(User::getNo, user.getNo()).list();
        if (!existingUsers.isEmpty()) {
            return Result.fail("用户已存在");
        }
        // 保存新用户
        userService.save(user);
        // 返回成功结果
        return Result.suc("注册成功");
    }
    @PostMapping("/mod")
    public  boolean mod(@RequestBody User user){
        return userService.updateById(user);
    }
    //新增或修改
    @PostMapping("/saveOrMod")
    public  boolean saveOrMod(@RequestBody User user){
        return userService.saveOrUpdate(user);
    }
    //    删除
    @GetMapping("/delete")
    public  boolean delete(Integer id){
        return  userService.removeById(id);
    }
    // 查询（模糊like、匹配eq（等于））
    @PostMapping("/listP")
    public  Result listP(@RequestBody User user){
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();

        if(StringUtils.isNotBlank(user.getName())){
            lambdaQueryWrapper.like(User::getName,user.getName());
        }
       return Result.suc(userService.list(lambdaQueryWrapper));
    }
    @PostMapping("/listPage")
//    public  List<User> listPage(@RequestBody HashMap map){
    public  List<User> listPage(@RequestBody QueryPageParam query){

//        System.out.println(query);
//        System.out.println("num==="+query.getPageNum());
//        System.out.println("size==="+query.getPageSize());
//        HashMap param = query.getParam();
//        System.out.println("name==="+param.get("name"));
//        System.out.println("no==="+param.get("no"));

////        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
////        lambdaQueryWrapper.eq(User::getName,user.getName());
////        return  userService.list(lambdaQueryWrapper);
        HashMap param = query.getParam();
        String name = (String) param.get("name");
        Page<User> page = new Page(1,2);
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(User::getName,name);
        IPage result = userService.page(page,lambdaQueryWrapper);
        System.out.println("total==="+result.getTotal());
        return  result.getRecords();
    }
    @PostMapping("/listPageC")
    public  List<User> listPageC(@RequestBody QueryPageParam query){
        HashMap param = query.getParam();
        String name = (String) param.get("name");
        String roleId = (String)param.get("name");
        System.out.println("name==="+(String)param.get("name") );
        Page<User> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(User::getName,name);
//        IPage result = userService.pageC(page);
        IPage result = userService.pageCC(page,lambdaQueryWrapper);

        System.out.println("total==="+result.getTotal());
        return  result.getRecords();
    }
    @PostMapping("/listPageC1")
    public Result listPageC1(@RequestBody QueryPageParam query){
        HashMap param = query.getParam();
        String name = (String) param.get("name");
        String sex  =(String) param.get("sex");
        String roleId  =(String) param.get("roleId");

        System.out.println("name==="+(String)param.get("name") );

        Page<User> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(name) && !"null".equals(name)){
            lambdaQueryWrapper.like(User::getName,name);
        }
        if(StringUtils.isNotBlank(sex)){
            lambdaQueryWrapper.eq(User::getSex,sex);
        }
        if(StringUtils.isNotBlank(roleId)){
            lambdaQueryWrapper.eq(User::getRoleId,roleId);
        }
//        IPage result = userService.pageC(page);
        IPage result = userService.pageCC(page,lambdaQueryWrapper);
        System.out.println("total==="+result.getTotal());

        return  Result.suc(result.getRecords(),result.getTotal());
    }
}
